package com.sc.nft.admin.consume;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.ObjectUtil;
import com.sc.nft.dao.*;
import com.sc.nft.dto.MetaMapSettleDTO;
import com.sc.nft.dto.UserCollectionSummaryDTO;
import com.sc.nft.entity.*;
import com.sc.nft.entity.vo.EcologyHatchMetaMapVO;
import com.sc.nft.enums.*;
import com.sc.nft.exception.GlobalRunTimeException;
import com.sc.nft.service.EcologyHatchRatioService;
import com.sc.nft.service.EquitySharePanelService;
import com.sc.nft.service.MallProfitTemplateService;
import com.sc.nft.service.ScrollConfigService;
import com.sc.nft.util.LocalDateTimeUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@RocketMQMessageListener(topic = MessageTopic.META_MAP_SETTLE + "${spring.profiles.active}", consumerGroup = MessageTopic.META_MAP_SETTLE + "${spring.profiles.active}")
@Component
@Slf4j
@RequiredArgsConstructor
public class MetaMapSettleConsumer implements RocketMQListener<MetaMapSettleDTO> {

    private final IdcardInfoDao idcardInfoDao;
    private final MetaMapSettleDao metaMapSettleDao;
    private final NftRegionBindingDao nftRegionBindingDao;
    private final UserCollectionDao userCollectionDao;
    private final ShareProfitDao shareProfitDao;
    private final EquitySharePanelService equitySharePanelService;
    private final ScrollConfigService scrollConfigService;
    private final EcologyHatchRatioService ecologyHatchRatioService;
    private final MallProfitTemplateService mallProfitTemplateService;
    private final RedissonClient redissonClient;
    private final FilterIncomeListDao filterIncomeListDao;
    private final AdministrativeAreaDao administrativeAreaDao;


    @Override
    @Transactional(rollbackFor = Exception.class)
    public void onMessage(MetaMapSettleDTO message) {
        String key = RedisKeyEnum.META_MAP_SETTLE.getKey() + message.getOrderNo();
        RLock lock = redissonClient.getLock(key);
        try {
            if (!lock.tryLock(30, TimeUnit.SECONDS)) {
                throw new GlobalRunTimeException("获取锁失败");
            }
            //判断是否是市值账号
            FilterIncomeList filterIncomeList = filterIncomeListDao.getIsTeamIncomeByUserId(message.getBuyUserId());
            if (ObjectUtil.isNotNull(filterIncomeList)) {
                metaMapSettleDao.save(message.turnDown("市值帐号不参加分润"));
                return;
            }
            //商城心愿金不参加分润
            if (MetaMapSettleSourceTypeEnum.MALL == message.getSourceType() && NumberUtil.isGreater(message.getWishBalancePrice(), BigDecimal.ZERO)) {
                metaMapSettleDao.save(message.turnDown("心愿金不参加分润"));
                return;
            }
            if (MetaMapSettleSourceTypeEnum.MALL == message.getSourceType()) {// 商城分润,商城走单独的逻辑
                mallFractional(message);
                return;
            }
            //执行分润
            for (RegionLevelEnum regionLevel : RegionLevelEnum.values()) {
                //检查分润前置条件
                Map<Long, UserCollectionSummaryDTO> userCollectionMaps = checkShareStatus(message, regionLevel);
                if (Objects.isNull(userCollectionMaps)) {
                    continue;
                }
                if (MetaMapSettleSourceTypeEnum.SMELTING == message.getSourceType()) {// 燃料分润
                    fuelFractional(message, userCollectionMaps, regionLevel);
                } else if (MetaMapSettleSourceTypeEnum.FIRST_ORDER == message.getSourceType()) {// 一级订单
                    firstOrderFractional(message, userCollectionMaps, regionLevel);
                } else if (MetaMapSettleSourceTypeEnum.PROP_ORDER == message.getSourceType()) {// 道具订单分润
                    propOrderFractional(message, userCollectionMaps, regionLevel);
                } else if (MetaMapSettleSourceTypeEnum.SECOND_ORDER == message.getSourceType()) {// 二级订单分润
                    secondOrderFractional(message, userCollectionMaps, regionLevel);
                } else if (MetaMapSettleSourceTypeEnum.SHOP == message.getSourceType()) {// 店铺分润
                    shopFractional(message, userCollectionMaps, regionLevel);
                } else {
                    metaMapSettleDao.save(message.turnDown("未知分润类型"));
                }
            }
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally {
            if (lock.isLocked() && lock.isHeldByCurrentThread()) {
                lock.unlock();
            }
        }
    }

    /**
     * 商城分润
     * @param message 消息体
     */
    private void mallFractional(MetaMapSettleDTO message) {
        // 分润模版
        MallProfitTemplate mallProfitTemplate = mallProfitTemplateService.getById(message.getShareProfitPanelId());
        if (BeanUtil.isEmpty(mallProfitTemplate)) {
            metaMapSettleDao.save(message.turnDown("商城模板id获取的数据不存在,无法分润"));
            return;
        }
        if (NumberUtil.isLessOrEqual(message.getParticipation(), BigDecimal.ZERO)) {
            metaMapSettleDao.save(message.turnDown("当前参与计算的值小于等于0,无法进行分润"));
            return;
        }
        // 通过省市区,获取绑定的哪个藏品.通过藏品获取谁在持有.有就开始分润 没有就不给,1个区可能会绑定多个藏品.如果有多个的情况下需要均分.
        List<NftRegionBinding> nftRegionBindings = nftRegionBindingDao.selectProvinceAndCityAndAreaAndEffectiveTime(message.getProvince(), message.getCity(), message.getArea());
        List<Long> collectionId = nftRegionBindings.stream().map(NftRegionBinding::getCollectionId).collect(Collectors.toList());
        if (CollectionUtils.isEmpty(collectionId)) {
            metaMapSettleDao.save(message.turnDown("商城查询的藏品id为空，无法进行分润"));
            return;
        }
        String provinceName = nftRegionBindings.get(0).getProvinceName();
        String cityName = nftRegionBindings.get(0).getCityName();
        String regionName = nftRegionBindings.get(0).getRegionName();
        StringBuilder stringBuilder = new StringBuilder();
        if (StringUtils.isNotBlank(provinceName)) {
            stringBuilder.append(provinceName);
        }
        if (StringUtils.isNotBlank(cityName)) {
            stringBuilder.append(cityName);
        }
        if (StringUtils.isNotBlank(regionName)) {
            stringBuilder.append(regionName);
        }

        List<UserCollection> userCollections = userCollectionDao.selectByCollectionIds(collectionId);
        for (UserCollection userCollection : userCollections) {
            // 保存分润记录
            MetaMapSettle metaMapSettle = message.turnDownPass();
            metaMapSettle.setCollectionId(userCollection.getCollectionId());
            metaMapSettle.setQuota(message.getParticipation());
            metaMapSettle.setDivide(mallProfitTemplate.getMapIncome());
            metaMapSettle.setMetaMap(stringBuilder.toString());
            metaMapSettle.setSourceType(MetaMapSettleSourceTypeEnum.MALL);
            metaMapSettle.setDescribeContent("该条目数据为商城数据,确认收货7日后,自动分润");
            metaMapSettle.setEarningsUserId(userCollection.getUserId());
            metaMapSettle.setDivideType(MetaMapSettleDivideTypeEnum.CHARGE_PRICE);
            metaMapSettle.setGetTime(DateUtil.date());
            metaMapSettle.setStatus(MetaMapSettleStatusEnum.ISSUED);
            metaMapSettleDao.save(metaMapSettle);
        }
    }

    /**
     * 店铺分润
     *
     * @param message 消息体
     * @param userCollectionSummaryMap 用户藏品
     */
    private void shopFractional(MetaMapSettleDTO message, Map<Long, UserCollectionSummaryDTO> userCollectionSummaryMap, RegionLevelEnum regionLevel) {
        // 根据模板id计算分钱总数
        ScrollConfig scrollConfig = scrollConfigService.getScrollConfigById(message.getShareProfitPanelId());
        if (BeanUtil.isEmpty(scrollConfig)) {
            metaMapSettleDao.save(message.turnDown("店铺模板id获取的数据不存在,无法分润"));
            return;
        }

        BigDecimal metaMapRatioValue = BigDecimal.ZERO;//分润比例
        if (regionLevel == RegionLevelEnum.PROVINCE) {
            metaMapRatioValue = scrollConfig.getMetaMapRatio();
        } else if (regionLevel == RegionLevelEnum.CITY) {
            metaMapRatioValue = scrollConfig.getMetaMapCityRatio();
        } else if (regionLevel == RegionLevelEnum.REGION) {
            metaMapRatioValue = scrollConfig.getMetaMapRegionRatio();
        }

        BigDecimal quota = getQuota(message, message.getCharge(), metaMapRatioValue, userCollectionSummaryMap);
        if (Objects.isNull(quota)) {
            return;
        }
        for (Map.Entry<Long, UserCollectionSummaryDTO> um : userCollectionSummaryMap.entrySet()) {
            Long userId = um.getKey();
            UserCollectionSummaryDTO userCollection = um.getValue();
            MetaMapSettle metaMapSettle = getMetaMapSettle(quota, userCollection, message, metaMapRatioValue);
            metaMapSettle.setSourceType(MetaMapSettleSourceTypeEnum.SHOP);
            metaMapSettle.setEarningsUserId(userId);
            metaMapSettle.setDivideType(MetaMapSettleDivideTypeEnum.CHARGE_PRICE);
            metaMapSettle.setGetTime(DateUtil.date());
            metaMapSettle.setStatus(MetaMapSettleStatusEnum.TO_BE_ISSUED);
            metaMapSettleDao.save(metaMapSettle);
        }
    }


    /**
     * 二级订单分润
     *
     * @param message 消息体
     * @param userCollectionSummaryMap 用户藏品
     */
    private void secondOrderFractional(MetaMapSettleDTO message, Map<Long, UserCollectionSummaryDTO> userCollectionSummaryMap, RegionLevelEnum regionLevelEnum) {
        ShareProfit shareProfit = firstOrderAndSecondOrderTemplate(message, regionLevelEnum);
        if (BeanUtil.isEmpty(shareProfit)) {
            return;
        }
        // 分润百分比
        BigDecimal shareRatio = shareProfit.getSumRatio();
        //获取分润金额
        BigDecimal quota = getQuota(message, message.getCharge(), shareRatio, userCollectionSummaryMap);
        if (Objects.isNull(quota)) {
            return;
        }
        // 遍历longIntegerMap,进行分润
        userCollectionSummaryMap.forEach((userId, userCollection) -> {
            MetaMapSettle metaMapSettle = getMetaMapSettle(quota, userCollection, message, shareRatio);
            metaMapSettle.setSourceType(MetaMapSettleSourceTypeEnum.SECOND_ORDER);
            metaMapSettle.setEarningsUserId(userId);
            metaMapSettle.setDivideType(MetaMapSettleDivideTypeEnum.CHARGE_PRICE);
            metaMapSettle.setGetTime(DateUtil.date());
            metaMapSettle.setStatus(MetaMapSettleStatusEnum.TO_BE_ISSUED);
            metaMapSettleDao.save(metaMapSettle);
        });
    }

    /**
     * 道具订单分润
     *
     * @param message 消息体
     * @param userCollectionSummaryMap 用户藏品统计
     */
    private void propOrderFractional(MetaMapSettleDTO message, Map<Long, UserCollectionSummaryDTO> userCollectionSummaryMap, RegionLevelEnum regionLevel) {
        // 根据模板id计算分钱总数
        EquitySharePanel panel = equitySharePanelService.getPanelById(message.getShareProfitPanelId());
        if (BeanUtil.isEmpty(panel)) {
            metaMapSettleDao.save(message.turnDown("道具模板id获取的数据不存在,无法分润"));
            return;
        }

        BigDecimal metaMapRatioValue = BigDecimal.ZERO;//分润比例
        if (regionLevel == RegionLevelEnum.PROVINCE) {
            metaMapRatioValue = panel.getMetaMapRatio();
        } else if (regionLevel == RegionLevelEnum.CITY) {
            metaMapRatioValue = panel.getMetaMapCityRatio();
        } else if (regionLevel == RegionLevelEnum.REGION) {
            metaMapRatioValue = panel.getMetaMapRegionRatio();
        }

        BigDecimal quota = getQuota(message, message.getCharge(), metaMapRatioValue, userCollectionSummaryMap);
        if (Objects.isNull(quota)) {
            return;
        }

        for (Map.Entry<Long, UserCollectionSummaryDTO> um : userCollectionSummaryMap.entrySet()) {
            Long userId = um.getKey();
            UserCollectionSummaryDTO userCollection = um.getValue();
            // 分润金额
            MetaMapSettle metaMapSettle = getMetaMapSettle(quota, userCollection, message, metaMapRatioValue);
            metaMapSettle.setSourceType(MetaMapSettleSourceTypeEnum.PROP_ORDER);
            metaMapSettle.setEarningsUserId(userId);
            metaMapSettle.setDivideType(MetaMapSettleDivideTypeEnum.CHARGE_PRICE);
            metaMapSettle.setGetTime(DateUtil.date());
            metaMapSettle.setStatus(MetaMapSettleStatusEnum.TO_BE_ISSUED);
            metaMapSettleDao.save(metaMapSettle);
        }
    }

    /**
     * 一级订单分润
     *
     * @param message 消息体
     * @param userCollectionSummaryMap 用户藏品
     */
    private void firstOrderFractional(MetaMapSettleDTO message, Map<Long, UserCollectionSummaryDTO> userCollectionSummaryMap, RegionLevelEnum regionLevelEnum) {
        ShareProfit shareProfit = firstOrderAndSecondOrderTemplate(message, regionLevelEnum);
        if (BeanUtil.isEmpty(shareProfit)) {
            return;
        }
        // 分润百分比
        BigDecimal shareRatio = shareProfit.getSumRatio();
        //获取分润金额
        BigDecimal quota = getQuota(message, message.getParticipation(), shareRatio, userCollectionSummaryMap);
        if (Objects.isNull(quota)) {
            return;
        }
        // 遍历longIntegerMap,进行分润
        userCollectionSummaryMap.forEach((userId, userCollection) -> {
            // 分润金额
            MetaMapSettle metaMapSettle = getMetaMapSettle(quota, userCollection, message, shareRatio);
            metaMapSettle.setSourceType(MetaMapSettleSourceTypeEnum.FIRST_ORDER);
            metaMapSettle.setEarningsUserId(userId);
            metaMapSettle.setDivideType(MetaMapSettleDivideTypeEnum.PARTICIPATE);
            metaMapSettle.setGetTime(DateUtil.date());
            metaMapSettle.setStatus(MetaMapSettleStatusEnum.TO_BE_ISSUED);
            metaMapSettleDao.save(metaMapSettle);
        });

    }

    /**
     * 燃料分润
     *
     * @param message 消息主体
     * @param userCollectionSummaryMap 用户藏品
     */
    private void fuelFractional(MetaMapSettleDTO message, Map<Long, UserCollectionSummaryDTO> userCollectionSummaryMap, RegionLevelEnum regionLevel) {
        //获取分润模版
        EcologyHatchMetaMapVO metaMapRatio = ecologyHatchRatioService.findMetaMapRatio();
        if (BeanUtil.isEmpty(metaMapRatio)) {
            metaMapSettleDao.save(message.turnDown("道具模板id获取的数据不存在,无法分润"));
            return;
        }

        BigDecimal metaMapRatioValue = BigDecimal.ZERO;//分润比例
        if (regionLevel == RegionLevelEnum.PROVINCE) {
            metaMapRatioValue = metaMapRatio.getMetaMapProvinceRatio();
        } else if (regionLevel == RegionLevelEnum.CITY) {
            metaMapRatioValue = metaMapRatio.getMetaMapCityRatio();
        } else if (regionLevel == RegionLevelEnum.REGION) {
            metaMapRatioValue = metaMapRatio.getMetaMapRegionRatio();
        }

        //获取分润金额
        BigDecimal quota = getQuota(message, message.getParticipation(), metaMapRatioValue, userCollectionSummaryMap);
        if (Objects.isNull(quota)) {
            return;
        }

        for (Map.Entry<Long, UserCollectionSummaryDTO> um : userCollectionSummaryMap.entrySet()) {
            Long userId = um.getKey();
            UserCollectionSummaryDTO userCollection = um.getValue();
            // 分润金额
            MetaMapSettle metaMapSettle = getMetaMapSettle(quota, userCollection, message, metaMapRatioValue);
            metaMapSettle.setSourceType(MetaMapSettleSourceTypeEnum.SMELTING);
            metaMapSettle.setEarningsUserId(userId);
            metaMapSettle.setMetaMap(metaMapSettle.getMetaMap() + "版图权益");
            metaMapSettle.setDivideType(MetaMapSettleDivideTypeEnum.PARTICIPATE);
            metaMapSettle.setGetTime(DateUtil.date());
            metaMapSettle.setStatus(MetaMapSettleStatusEnum.TO_BE_ISSUED);
            metaMapSettleDao.save(metaMapSettle);
        }
    }


    /**
     * 验证分润的前置,看当前该条数据是否进行分润.
     *
     * @return 返回一个Map<Long, Integer>  key为用户id,value为用户持有的藏品数量,在调用方自行汇总后,进行分润.
     */
    public Map<Long, UserCollectionSummaryDTO> checkShareStatus(MetaMapSettleDTO metaMapSettleDTO, RegionLevelEnum regionLevel) {
        //  通过购买人获取购买人身份证,拿到他前六位让后通过行政编号去查询
        IdcardInfo idcardInfo = idcardInfoDao.findLastOneByUserId(metaMapSettleDTO.getBuyUserId());
        // 当前用户如果说没有身份证,那么就不进行分润,但是要记录. 虽然不会发生,但是真的发生了怕找不到.防备一手,防止有人拉屎
        if (BeanUtil.isEmpty(idcardInfo)) {
            metaMapSettleDao.save(metaMapSettleDTO.turnDown("当前用户没有身份认证,无法进行分润"));
            return null;
        }
        // 获取用户身份证前六位
        String idCard = idcardInfo.getCardId();
        if (StringUtils.isBlank(idCard) || idCard.length() < 6) {
            metaMapSettleDao.save(metaMapSettleDTO.turnDown("身份证解析错误"));
            return null;
        }
        if (regionLevel == RegionLevelEnum.PROVINCE) {
            idCard = idCard.substring(0, 2);
        } else if (regionLevel == RegionLevelEnum.CITY) {
            idCard = idCard.substring(0, 4);
        } else if (regionLevel == RegionLevelEnum.REGION) {
            idCard = idCard.substring(0, 6);
        }
        // 通过前六位去查询行政编号
        AdministrativeArea administrationCode = administrativeAreaDao.administrationCode(idCard);
        if (BeanUtil.isEmpty(administrationCode)) {
            metaMapSettleDao.save(metaMapSettleDTO.turnDown("当前用户行政编号查询不存在,无法进行分润"));
            return null;
        }
        if (Objects.isNull(administrationCode.getRegionId())) {
            metaMapSettleDao.save(metaMapSettleDTO.turnDown("当前用户上级行政编号不存在,无法进行分润"));
            return null;
        }
        Long province = regionLevel == RegionLevelEnum.PROVINCE ? administrationCode.getRegionId() : null;
        Long city = regionLevel == RegionLevelEnum.CITY ? administrationCode.getRegionId() : null;
        Long region = regionLevel == RegionLevelEnum.REGION ? administrationCode.getRegionId() : null;
        // 通过行政编号去查询藏品id
        List<NftRegionBinding> nftRegionBindings = nftRegionBindingDao.selectProvinceIdAndCityIdAndAreaIdAndCollectionId(null, province, city, region, regionLevel);
        if (CollUtil.isEmpty(nftRegionBindings)) {
            metaMapSettleDao.save(metaMapSettleDTO.turnDown("当前用户行政编号查询藏品id不存在,无法进行分润"));
            return null;
        }
        NftRegionBinding nftRegionBinding = nftRegionBindings.get(0);
        if (Objects.isNull(nftRegionBinding.getEffectiveTime())) {
            metaMapSettleDao.save(metaMapSettleDTO.turnDown("权益有效时间为空 无法分润"));
            return null;
        }
        LocalDateTime date = LocalDateTimeUtil.dateToLocalDateTime(nftRegionBinding.getEffectiveTime());
        if (date.isBefore(LocalDateTime.now())) {
            metaMapSettleDao.save(metaMapSettleDTO.turnDown("权益无有效时间 无法分润,订单发送时间:" + metaMapSettleDTO.getSendTime() + ",权益到期时间:" + date.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"))));
            return null;
        }
        metaMapSettleDTO.setProvince(nftRegionBinding.getProvinceName());
        metaMapSettleDTO.setCity(nftRegionBinding.getCityName());
        metaMapSettleDTO.setArea(nftRegionBinding.getRegionName());
        // 查出来都有哪些用户持这些藏品,把这些用户获取出来,返回去,给这些用户分润.
        List<UserCollection> userCollections = userCollectionDao.selectByCollectionIdsIsHold(nftRegionBindings.stream().map(NftRegionBinding::getCollectionId).collect(Collectors.toList()));
        // 对userCollections进行中的userId进行分组,在汇总每个用户所持有的总数 使用Map<Long,userCollectionSummaryDTO>形式组装
        return userCollections.stream()
                .collect(Collectors.groupingBy(
                        UserCollection::getUserId,
                        Collectors.collectingAndThen(
                                Collectors.toList(),
                                list -> {
                                    UserCollectionSummaryDTO userCollectionSummaryDTO = new UserCollectionSummaryDTO();
                                    userCollectionSummaryDTO.setCollectionIds(list.stream().map(UserCollection::getCollectionId).collect(Collectors.toList()));
                                    userCollectionSummaryDTO.setCount(list.size());
                                    return userCollectionSummaryDTO;
                                }
                        )
                ));
    }


    /**
     * 获取分润记录对象
     * @param quota 分润总额
     * @param userCollection 用户藏品
     * @param message 消息体
     * @param percentage 分润比例
     * @return MetaMapSettle 分润记录对象
     */
    private static MetaMapSettle getMetaMapSettle(BigDecimal quota, UserCollectionSummaryDTO userCollection, MetaMapSettleDTO message, BigDecimal percentage) {
        // 分润金额
        BigDecimal divideAmount = quota.multiply(new BigDecimal(userCollection.getCount())).setScale(2, RoundingMode.DOWN);
        // 保存分润记录
        MetaMapSettle metaMapSettle = message.turnDownPass();
        List<Long> collectionIds = userCollection.getCollectionIds();
        metaMapSettle.setCollectionId(CollectionUtils.isNotEmpty(collectionIds) ? collectionIds.get(0) : 0L);
        metaMapSettle.setQuota(divideAmount);
        metaMapSettle.setDivide(percentage);
        return metaMapSettle;
    }


    /**
     * 一二级订单分润模板
     *
     * @param message 消息体
     * @return ShareProfit
     */
    private ShareProfit firstOrderAndSecondOrderTemplate(MetaMapSettleDTO message, RegionLevelEnum regionLevelEnum) {
        DivideTypeEnum divideTypeEnum = null;
        if (regionLevelEnum == RegionLevelEnum.PROVINCE) {
            divideTypeEnum = DivideTypeEnum.MATE_MAP_PROVINCE;
        } else if (regionLevelEnum == RegionLevelEnum.CITY) {
            divideTypeEnum = DivideTypeEnum.MATE_MAP_CITY;
        } else if (regionLevelEnum == RegionLevelEnum.REGION) {
            divideTypeEnum = DivideTypeEnum.MATE_MAP_REGION;
        }
        // 根据模板id计算分钱总数
        List<ShareProfit> byPanelIdAndType = shareProfitDao.getByPanelIdAndType(message.getShareProfitPanelId(), divideTypeEnum);
        if (CollUtil.isEmpty(byPanelIdAndType)) {
            metaMapSettleDao.save(message.turnDown("模板id获取的数据不存在,无法分润"));
            return null;
        }
        ShareProfit shareProfit = byPanelIdAndType.get(0);
        if (BeanUtil.isEmpty(shareProfit)) {
            metaMapSettleDao.save(message.turnDown("模板id获取的数据不存在,无法分润"));
            return null;
        }
        return shareProfit;
    }

    /**
     * 获取分润金额
     * @param metaMapSettle 分润记录对象
     * @param total 分润总额
     * @param percentage 分润比例
     * @param userCollectionMaps 用户藏品
     * @return 分润金额
     */
    private BigDecimal getQuota(MetaMapSettleDTO metaMapSettle, BigDecimal total, BigDecimal percentage, Map<Long, UserCollectionSummaryDTO> userCollectionMaps) {
        if (NumberUtil.isLessOrEqual(total, BigDecimal.ZERO)) {
            metaMapSettleDao.save(metaMapSettle.turnDown("当前参与计算的总额小于等于0,无法进行分润"));
            return null;
        }
        if (Objects.isNull(percentage)) {
            metaMapSettleDao.save(metaMapSettle.turnDown("当前参与计算的比例为空,无法进行分润"));
            return null;
        }
        if (NumberUtil.isLessOrEqual(percentage, BigDecimal.ZERO)) {
            metaMapSettleDao.save(metaMapSettle.turnDown("当前参与计算的比例小于等于0,无法进行分润"));
            return null;
        }
        // 分润总额乘以分润百分比
        BigDecimal divide = total.multiply(percentage);
        if (NumberUtil.isLessOrEqual(divide, BigDecimal.ZERO)) {
            metaMapSettleDao.save(metaMapSettle.turnDown("分润金额为0,无法分润"));
            return null;
        }
        // 获取每一份的分润金额 userCollectionMaps的值汇总
        long sum = userCollectionMaps.values().stream().mapToLong(UserCollectionSummaryDTO::getCount).sum();
        if (sum <= 0L) {
            metaMapSettleDao.save(metaMapSettle.turnDown("分润人不存在"));
            return null;
        }
        // 分润金额除以总数,得到每一份的分润金额
        return divide.divide(new BigDecimal(sum), 2, RoundingMode.DOWN);
    }
}
